<?php

class MemberModel extends Model
{
    // 自动完成
    protected $_auto = array(
        array('reg_ip', 'get_client_ip', self::MODEL_INSERT, 'function', 1),
        array('reg_time', NOW_TIME, self::MODEL_INSERT),
        array('last_login_ip', 0, self::MODEL_INSERT),
        array('last_login_time', 0, self::MODEL_INSERT),
        array('status', 1, self::MODEL_INSERT),
    );


    public function login($uid)
    {
        $user = $this->find($uid);

        if (!$user) {
            $Api = A('User/User', 'Api');
            $userinfo = $Api->getUserInfo($uid);
            $arr = array(
                'username' => $userinfo[1],
                'email' => $userinfo[2],
            );
            $data = $this->create($arr);
            $data['uid'] = $userinfo[0];

            if (!$this->add($data)) {
                $this->error = '注册该应用失败!';
                return false;
            }

        } elseif (1 != $user['status']) {
            $this->error = '用户未激活或已禁用！';
            return false;
        }

        $this->autoLogin($user);
        return true;
    }


    private function autoLogin($user)
    {
        $data = array(
            'uid' => $user['uid'],
            'last_login_time' => NOW_TIME,
            'last_login_ip' => get_client_ip(1),

        );

        $res = $this->save($data);

        $auth = array(
            'uid' => $user['uid'],
            'username' => $user['username'],
            'last_login_time' => $user['last_login_time'],
        );

        session('user_auth', $auth);

    }
}